package edu.yuhf.web.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.yuhf.utils.ConvertUtils;

import edu.yuhf.dao.iface.ImageDao;
import edu.yuhf.entity.Image;

@Controller
@RequestMapping(value = "/utils") 
public class UploadController {
	
	@Resource
	ImageDao imageDao;
	
	@RequestMapping(value="/getImage")
	public String getIamge(@RequestParam(value="id") String id,HttpServletResponse response) throws IOException, SQLException{
		Image image=imageDao.getImage(Integer.valueOf(id));
		response.setHeader("Content-Type","image/jped");
		byte[] b=ConvertUtils.toByte(image.getImage());
		response.getOutputStream().write(b);
		response.flushBuffer();
		return null;
	}
	
    @RequestMapping(value = "/doUpload")  
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {  

    	String name=request.getParameter("name");
    	System.out.println(name);
    	//MultipartFile -> java.io.File
        CommonsMultipartFile cf= (CommonsMultipartFile)file; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
        File f = fi.getStoreLocation(); 
    	int id=imageDao.insertImage(f);


        String path = request.getSession().getServletContext().getRealPath("upload");  
        String fileName = file.getOriginalFilename();  
//      String fileName = new Date().getTime()+".jpg";  
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
        model.addAttribute("imageId",id);
        return "views/fileupload/uploadResult";  
    } 
}
